package top.itlir.edc.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import top.itlir.edc.dao.PermissionRepository;
import top.itlir.edc.dao.UserRepository;
import top.itlir.edc.domain.Permission;
import top.itlir.edc.domain.Role;
import top.itlir.edc.domain.User;
import top.itlir.edc.service.IPermissionService;

@Service
@Transactional
public class PermissionServiceImpl implements IPermissionService {

	@Resource
	private PermissionRepository permissionRepository;
	
	@Resource
	private UserRepository userRepository;

	@Override
	public Page<Permission> findAll(Specification<Permission> spec,
			Pageable pageable) {
		return permissionRepository.findAll(spec, pageable);
	}

	@Override
	public void save(Permission model) {
		permissionRepository.save(model);
	}

	@Override
	public List<Permission> findAll2() {
		return permissionRepository.findAll();
	}

	@Override
	public List<Permission> findPermissionByUser(User user) {
		if ("admin".equals(user.getUsername())) {
			return permissionRepository.findAll();
		} else {
			User userRep  = userRepository.findOne(user.getId());
			Set<Role> roles = userRep.getRoles();
			ArrayList<Permission> arrayList = new ArrayList<Permission>();
			
			if (null != roles && roles.size() > 0) {
				for (Role role : roles) {
					arrayList.addAll(role.getPermissions());
				}
			}
			return arrayList;
		}
	}


}
